/**
 * @author Teacher Gong
 * @note 收支编辑界面
 */

package team.wh1tegive.cg;

import team.wh1tegive.misc.Log;
import team.wh1tegive.user.CashFlow;
import team.wh1tegive.user.User;
import team.wh1tegive.user.UserAction;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

class BalEditFrame extends JFrame implements ActionListener {
    public MouseAdapter ma;
    public int line;
    String[] cloum = new String[]{"编号", "日期", "类型", "内容", "金额"};
    int i = 0;
    //  private Vector<String> row,data,names;//行向量，行向量集，列向量
    ArrayList<CashFlow> cfl = new ArrayList<>();
    Container c;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    private JLabel l_id, l_date, l_bal, l_type, l_item;
    private JTextField t_id, t_date, t_bal;
    private JComboBox c_type, c_item;
    private JButton b_update, b_delete, b_select, b_new, b_clear;
    private JPanel p1, p2, p3;
    private JScrollPane scrollpane;
    private JTable table;
    private java.lang.Object Object;
    private User user;
    private DefaultTableModel dtm;
    private Object[][] row;

    public BalEditFrame(User user) {
        super("收支编辑");
        this.user = user;
        l_id = new JLabel("编号：");
        l_date = new JLabel("日期：");
        l_bal = new JLabel("金额：");
        l_type = new JLabel("类型：");
        l_item = new JLabel("内容：");
        t_id = new JTextField(8);
        t_date = new JTextField(8);
        t_bal = new JTextField(8);
        ma = new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                line = table.getSelectedRow();
                String val = (String) table.getModel().getValueAt(line, 0);
                t_id.setText(val);
                t_date.setText((String) table.getModel().getValueAt(line, 1));
                t_bal.setText(table.getModel().getValueAt(line, 4).toString());
                t_id.setEditable(false);

            }
        };

        String s1[] = {"收入", "支出"};
        String s2[] = {"购物", "餐饮", "居家", "交通", "娱乐", "人情", "工资", "奖金", "其他"};
        c_type = new JComboBox(s1);
        c_item = new JComboBox(s2);

        b_select = new JButton("查询");
        b_update = new JButton("修改");
        b_delete = new JButton("删除");
        b_new = new JButton("录入");
        b_clear = new JButton("清空");


        c = this.getContentPane();
        c.setLayout(new BorderLayout());

        p1 = new JPanel();
        p1.setLayout(new GridLayout(5, 2, 10, 10));
        p1.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createTitledBorder("编辑收支信息"),
                BorderFactory.createEmptyBorder(5, 5, 5, 5)));
        p1.add(l_id);
        p1.add(t_id);
        p1.add(l_date);
        p1.add(t_date);
        p1.add(l_type);
        p1.add(c_type);
        p1.add(l_item);
        p1.add(c_item);
        p1.add(l_bal);
        p1.add(t_bal);
        c.add(p1, BorderLayout.WEST);

        p2 = new JPanel();
        p2.setLayout(new GridLayout(5, 1, 10, 10));
        p2.add(b_new);
        p2.add(b_update);
        p2.add(b_delete);
        p2.add(b_select);
        p2.add(b_clear);

        c.add(p2, BorderLayout.CENTER);

        p3 = new JPanel();
        p3.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createTitledBorder("显示收支信息"),
                BorderFactory.createEmptyBorder(5, 5, 5, 5)));


        row = new Object[50][5];

        table = new JTable(row, cloum);

        scrollpane = new JScrollPane(table);

        scrollpane.setViewportView(table);
        scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        p3.add(scrollpane);
        c.add(p3, BorderLayout.EAST);
        b_update.addActionListener(this);
        b_delete.addActionListener(this);
        b_select.addActionListener(this);
        b_new.addActionListener(this);
        b_clear.addActionListener(this);


        table.addMouseListener(ma);

        this.setResizable(false);
        this.setSize(800, 300);
        Dimension screen = this.getToolkit().getScreenSize();
        this.setLocation((screen.width - this.getSize().width) / 2, (screen.height - this.getSize().height) / 2);
        this.setVisible(true);
    }

//    private void addMouseListener(ActionEvent e) {
//        if(table==e.getSource())
//    }

    public void actionPerformed(ActionEvent e) {
        if (b_select == e.getSource()) {  //查询所有收支信息
            ShowTable();
            JOptionPane.showMessageDialog(null, "查询所有收支信息成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
            Log.writeLog(" Successfully Select * from UserAction.");

        } else if (b_update == e.getSource()) { //更新某条信息
            if (CheckTimeInput()) {
                CashFlow cf = getAllText();
                if (cf != null) {
                    if (user.UserActionUpdate(cf)) {
                        addRow(cf, line);
                        //Balance();//余额刷新
                        JOptionPane.showMessageDialog(null, "修改成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                        Log.writeLog(" Successfully update UserAction.");
                        //清空输入
                        t_date.setText("");
                        t_bal.setText("");
                        t_id.setText("");
                        t_id.setEditable(true);
                    } else Log.writeError(" Update.in Failed.");
                } else JOptionPane.showMessageDialog(null, "插入失败，金额错误。", "警告", JOptionPane.ERROR_MESSAGE);
                t_id.setEditable(true);
                t_id.setText("");
            }
        } else if (b_delete == e.getSource()) {   //删除某条收支信息
            //添加代码
            CashFlow cF = getRow(line);
            if (user.UserActionDelete(cF)) {
                JOptionPane.showMessageDialog(null, "删除成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                Log.writeLog(" Successfully delete UserAction.");
                ShowTable();
                t_date.setText("");
                t_bal.setText("");
                t_id.setText("");
                t_id.setEditable(true);
            } else {
                Log.writeError("delete.in Failed");
                JOptionPane.showMessageDialog(null, "删除失败！", "失败", JOptionPane.ERROR_MESSAGE);
            }
        } else if (b_new == e.getSource()) {   //新增某条收支信息
            if (CheckTimeInput()) {//时间输入检查
                CashFlow cf = getAllText();
                if (cf != null)
                    if (!UserAction.aidCheck(cf.actionId)) {//没有重复,插入数据tom库
                        if (user.UserActionInsert(cf)) {
                            JOptionPane.showMessageDialog(null, "录入成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                            addRow(cf, i++);
                            Log.writeLog(" Successfully Insert UserAction.");
                        } else {
                            JOptionPane.showMessageDialog(null, "插入失败，请详情查看日志。", "警告", JOptionPane.ERROR_MESSAGE);
                            Log.writeError("Insert UserAction Failed.");
                        }
                    } else {//有重复,取消插入,重置文本框
                        JOptionPane.showMessageDialog(null, "编号输入重复，请仔细检查！", "警告", JOptionPane.ERROR_MESSAGE);
                        Log.writeError(" Log.in Failed.");
                    }
                else JOptionPane.showMessageDialog(null, "插入失败，金额错误。", "警告", JOptionPane.ERROR_MESSAGE);
                t_bal.setText("");
                t_date.setText("");
                t_id.setText("");
            }
        } else if (b_clear == e.getSource()) {   //清空输入框
            //添加代码
            row = new Object[50][5];
            table = new JTable(row, cloum);
            t_bal.setText("");
            t_date.setText("");
            t_id.setText("");
        }
    }

    public void addRow(CashFlow cf, int i) {
        table.getModel().setValueAt(cf.actionId, i, 0);
        table.getModel().setValueAt(cf.date, i, 1);
        table.getModel().setValueAt(cf.isInCome, i, 2);
        table.getModel().setValueAt(cf.info, i, 3);
        table.getModel().setValueAt(cf.amount, i, 4);
    }

    public CashFlow getRow(int line) {
        String aid = (String) table.getModel().getValueAt(line, 0);
        String info = (String) table.getModel().getValueAt(line, 1);
        String date = (String) table.getModel().getValueAt(line, 2);
        String type = (String) table.getModel().getValueAt(line, 3);
        double amount = (double) table.getModel().getValueAt(line, 4);
        CashFlow cF = new CashFlow(aid, date, type, info, amount);
        return cF;
    }

    public CashFlow getAllText() {
        try {
            String aid = t_id.getText();
            String info = c_item.getSelectedItem().toString().trim();
            String date = t_date.getText();
            String type = c_type.getSelectedItem().toString().trim();
            double amount = Double.parseDouble(t_bal.getText());
            CashFlow cf = new CashFlow(aid, date, type, info, amount);
            return cf;
        } catch (NumberFormatException nfe) {
            Log.writeError("Amount Format Error!");
            return null;
        }
    }

    public void ShowTable() {
        try {
            i = 0;
            ArrayList<CashFlow> cfl = user.UASelect();
            for (CashFlow cf : cfl) {
                addRow(cf, i++);
            }
            Log.writeLog("Show Table Successfully.");
        } catch (Exception exception) {
            Log.writeError("Show Table Failed.");
        }
    }

    public boolean CheckTimeInput() {
        try {
            Date date = sdf.parse(t_date.getText());
        } catch (ParseException e) {
            JOptionPane.showMessageDialog(null, "输入时间格式错误，请重新输入", "警告", JOptionPane.ERROR_MESSAGE);
            t_date.setText("");
            Log.writeError("Time Format Error!");
            return false;
        }
        return true;
    }
}
